# $Id: server.py 83306ac00e39 2013/03/03 02:04:53 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
__version__  = "$Revision: 83306ac00e39 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2013-03-03 02:04:53Z $"

import SocketServer
import flowlib
import struct
from venya.lib import stdlib

FlowServer = SocketServer.UDPServer
NetFlowPackets = []
TemplateHeaders = []
OptionsTemplate = []

class FlowRequestHandler(SocketServer.DatagramRequestHandler):
   def handle(self):
      packet = ""
      for ix in self.rfile.readlines():
         packet += ix

      pktlen = len(packet)
      if pktlen == 0:
         self.warn("ignoring netflow packet from %s, size is zero", address)
      elif pktlen < 20:
         self.warn("invalid netflow packet, length %d, client: %s", pktlen,
               address)
      elif pktlen >= 20:
         pkthdr = flowlib.NetFlowHeader(packet)
         if pkthdr.flowtype == 0:
            print("%d, template flow set" %pkthdr.sequence)
            pkthdr.AddTemplateFlowSet(packet)
            TemplateHeaders.append(pkthdr)
         elif pkthdr.flowtype == 1:
            print("%d, options template flow set" %pkthdr.sequence)
            # pkthdr.AddOptionsTemplateFlowSet(packet)
         elif pkthdr.flowtype > 255:
            template = None
            if len(TemplateHeaders):
               template = TemplateHeaders[len(TemplateHeaders) - 1]
               print(int(template))

            pkthdr.AddDataFlowSet(packet)

